package com.hb.trade.server.project.section.service.raw.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hb.core.pojo.RoleDataAuthEntity;
import com.hb.core.pojo.enums.*;
import com.hb.core.pojo.parent.PageResult;
import com.hb.core.pojo.project.evaluation.vo.EvaluationProjectAndSectionInfoVO;
import com.hb.core.pojo.project.homepage.dto.StatisticUserParam;
import com.hb.core.pojo.project.homepage.vo.BidSectionStatisticVO;
import com.hb.core.pojo.project.notice.dto.TenderInviteEnterpriseDTO;
import com.hb.core.pojo.project.notice.entity.Notice;
import com.hb.core.pojo.project.opening.entity.OpeningBidInfo;
import com.hb.core.pojo.project.opening.mapper.OpeningBidInfoMapper;
import com.hb.core.pojo.project.proj.dto.BidProjectDTO;
import com.hb.core.pojo.project.proj.entity.AbstractProject;
import com.hb.core.pojo.project.section.dto.BidSectionDTO;
import com.hb.core.pojo.project.section.dto.BidSectionTenderDTO;
import com.hb.core.pojo.project.section.dto.SupplyBidSignupDTO;
import com.hb.core.pojo.project.section.entity.BidSection;
import com.hb.core.pojo.project.section.entity.BidSectionTender;
import com.hb.core.pojo.project.section.mapper.BidSectionMapper;
import com.hb.core.pojo.project.section.mapper.BidSectionTenderMapper;
import com.hb.core.pojo.project.section.mapper.SupplyBidSignupMapper;
import com.hb.trade.server.project.file.service.BidBuyRecordService;
import com.hb.trade.server.project.notice.service.NoticeService;
import com.hb.trade.server.project.order.service.UserOrderService;
import com.hb.trade.server.project.section.manager.BidSectionManager;
import com.hb.trade.server.project.section.service.raw.BidDownRecordService;
import com.hb.trade.server.project.section.service.raw.BidSectionService;
import com.hb.trade.server.project.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.fzzn.core.model.enums.LogicEnum;
import org.fzzn.core.util.Enums;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 采购方案/标段(包)信息表 服务实现类
 * </p>
 *
 * @author zhaojk
 * @since 2021-08-30
 */
@Service
public class BidSectionServiceImpl extends ServiceImpl<BidSectionMapper, BidSection> implements BidSectionService {

    @Resource
    private BidSectionTenderMapper bidSectionTenderMapper;
    @Resource
    private OpeningBidInfoMapper openingBidInfoMapper;

    /**
     * @param projectId: 项目id
     * @Description: 根据项目查询已经发布过公告(除控制价公告)的的标段列表
     * @Author: zhongdl
     * @Date:2021/12/27 14:57
     * @return: {@link List< BidSection> }
     **/
    @Override
    public List<BidSection> listReleaseNotice(Long projectId) {
        return baseMapper.listReleaseNotice(projectId);
    }

    /**
     * 根据项目id查询所有的标段
     *
     * @param projectId
     * @return
     */
    @Override
    public List<BidSectionDTO> findByProjectId(Long projectId) {
        QueryWrapper<BidSection> queryWrapper = new QueryWrapper<>();
        if (projectId != null) {
            queryWrapper.lambda().eq(BidSection::getProjectId, projectId);
        }
        queryWrapper.select("`id`, `project_id`, `file_id`, `sort_code`, `section_code`, `section_name`, `price`, `section_status`, `open_bid_time`, `clarification_submission_end_time`, `document_sale_start_time`, `document_sale_end_time`, `limit_config_info`, `price_per_package`, `bond`, `bond_str`, `bond_flag`, `bond_pay_type`, `control_price`, `price_form`, `billing_method`, `collection_method`, `monitor_name`, `guarantee_flag`, `qual_way`, `estimated_contract_price`, `section_content`, `consortium_bidding_flag`, `opening_set_id`, `sign_start_time`, `sign_end_time`, `two_stage_flag`, `sign_up_flag`, `sign_up_collection_id`, `registration_fee_flag`, `registration_fee_money`, `sys_collection_id`, `system_use_fee`, `invitation_start_time`, `invitation_end_time`");
        // 查询标段信息的原始数据
        List<BidSection> rawSections = this.list(queryWrapper);

        // 标段数据传输对象
        List<BidSectionDTO> sectionDtos = CollUtil.list(false);

        for (BidSection rawSection : rawSections) {
            BidSectionDTO sectionDto = rawSection.to(BidSectionDTO.class);
            // 设置标段状态名称
            Long sectionStatus = sectionDto.getSectionStatus();
            SectionStatusEnum ins = SectionStatusEnum.getIns(sectionStatus);
            if (ins != null) {
                sectionDto.setSectionStatusName(ins.getShowName());
            }
            sectionDtos.add(sectionDto);
        }
        return sectionDtos;
    }

    /**
     * 根据公告的id去查询所有的标段售价
     *
     * @param noticeId
     * @return
     */
    @Override
    public List<JSONObject> findSectionPriceByNoticeId(Long noticeId) {
        if (noticeId == null) {
            return new ArrayList<>();
        }
        return baseMapper.findSectionPriceByNoticeId(noticeId);
    }

    @Override
    public boolean saveSections(Long projectId, String projectCode, List<BidSectionDTO> sections) {
        return saveSections(projectId, projectCode, null, sections);
    }

    @Override
    public boolean saveSections(Long projectId, String projectCode, String tenderProjectCode, List<BidSectionDTO> sections) {
        return saveSections(projectId, projectCode, tenderProjectCode, null, sections);
    }

    @Override
    public boolean saveSections(Long projectId, String projectCode, String tenderProjectCode, Integer signUpFlag, List<BidSectionDTO> sections) {
        // 项目ID和方案ID不能同时为空, 分别对应保存项目和保存方案的操作
        if (projectId == null) {
            return false;
        }
        // 标段索引
        int size = sections.size();
        for (int i = 0; i < size; i++) {
            BidSectionDTO sectionDto = sections.get(i);
            sectionDto.setProjectId(projectId);
            sectionDto.setSortCode(i);

            if (StrUtil.isNotEmpty(tenderProjectCode)) {
                // 标段编号为项目编号 + 标段索引
                sectionDto.setSectionCode(tenderProjectCode + StringUtils.leftPad((i + 1) + "", 3, "0"));
            }
            if (signUpFlag != null && sectionDto.getSignUpFlag() == null) {
                sectionDto.setSignUpFlag(signUpFlag);
            }

            sectionDto.setSectionStatus(SectionStatusEnum.PROJECT_SAVED.getId());
            sectionDto.buildBaseData("");
            saveOrUpdate(sectionDto);
        }
        return true;
    }

    /**
     * 根据公告id去查询所有的标段信息
     *
     * @param noticeId
     * @return
     */
    @Override
    public List<BidSectionDTO> findSectionBondByNoticeId(Long noticeId) {
        return baseMapper.findSectionBondByNoticeId(noticeId);
    }

    @Override
    public List<BidSectionDTO> getSectionsByNoticeId(Long noticeId) {
        if (noticeId == null) {
            return CollUtil.list(false);
        }
        return baseMapper.getSectionsByNoticeId(noticeId);
    }

    /**
     * 根据标段id查询标段信息和项目信息
     *
     * @param sectionId
     * @return
     */
    @Override
    public BidSectionDTO findBidAndProjectBySectionId(Long sectionId) {
        return baseMapper.getBidAndProjectBySectionId(sectionId);
    }

    /**
     * 根据标段id查询项目和标段信息（评标系统页面显示用）
     *
     * @param sectionId
     * @return
     */
    @Override
    public EvaluationProjectAndSectionInfoVO bidProjectAndSectionInfoBySectionId(Long sectionId) {
        return baseMapper.bidProjectAndSectionInfoBySectionId(sectionId);
    }

    @Override
    public List<BidSection> listSections(Long sectionId) {
        return baseMapper.listSections(sectionId);
    }

    /**
     * 根据标段id查询最高限价信息
     *
     * @param sectionId
     * @return
     */
    @Override
    public List<BidSection> findLimitConfigInfoBySectionId(Long sectionId) {
        return baseMapper.findLimitConfigInfoBySectionId(sectionId);
    }

    @Override
    public Long getProId(Long sectionId) {
        if (sectionId == null) {
            return null;
        }
        BidSection section = getById(sectionId);
        if (section == null) {
            return null;
        }
        return section.getProjectId();
    }

    @Override
    public List<BidSectionDTO> allSections() {
        return baseMapper.allSections();
    }

    @Override
    public List<JSONObject> listConsoleItems(Long statusId, Integer roleSign, Integer bidWay) {
        if (statusId == null) {
            log.warn("statusId: [" + statusId + "]为空, 将忽略该查询条件");
        }

        if (roleSign == null) {
            log.warn("roleSign: [" + roleSign + "]为空, 将忽略该查询条件");
        }

        if (bidWay == null) {
            log.warn("bidWay: [" + bidWay + "]为空, 将忽略该查询条件");
        }

        // 获取标段状态
        return baseMapper.listConsoleItems(statusId, roleSign, bidWay);
    }

    /**
     * 根据项目id 查询标段
     *
     * @param bidSectionDTO
     * @return
     */
    @Override
    public Page<BidSectionDTO> selectListByProjectId(BidSectionDTO bidSectionDTO) {
        Page<BidSectionDTO> pages = bidSectionDTO.pages();
        Page<BidSectionDTO> page = baseMapper.selectListByProjectId(pages, bidSectionDTO);
        return page;
    }

    @Override
    public Object findBidSectionList(BidSectionDTO bidSection) {
        Integer pageFlag = bidSection.getPageFlag();
        if (pageFlag == null) {
            pageFlag = 1;
        }
        // 返回分页对象
        if (Integer.valueOf(1).equals(pageFlag)) {
            return pageBidSectionDTO(bidSection);
        }
        //不返回分页对象
        return findBidSectionArr(bidSection);
    }

    /**
     * @param bidSection: 根据
     * @Description: 分页查询标段列表 传fileId 就查招标文件下的标段 传项目id就查项目id下的标段
     * @Author: zhongdl
     * @Date:2021/12/15 16:05
     * @return: {@link com.hb.core.pojo.parent.PageResult< BidSection> }
     **/
    @Override
    public PageResult<BidSection> pageBidSectionDTO(BidSectionDTO bidSection) {
        Page<BidSection> pages = bidSection.pages();

        BidSection section = bidSection.to(BidSection.class);
        QueryWrapper<BidSection> bidSectionQueryWrapper = section.buildWrapper();

        BidSectionManager sectionManager = bidSection.to(BidSectionManager.class);

        // 添加其他的查询条件
        sectionManager.buildQueryType(bidSectionQueryWrapper, bidSection.getProjectId());

        page(pages, bidSectionQueryWrapper);

        return PageResult.get(pages);
    }

    /**
     * @param bidSection:
     * @Description: 查询标段列表 传fileId 就查招标文件下的标段 传项目id就查项目id下的标段
     * @Author: zhongdl
     * @Date:2021/12/15 16:29
     * @return: {@link List< BidSection> }
     **/
    @Override
    public List<BidSection> findBidSectionArr(BidSectionDTO bidSection) {
        BidSection section = bidSection.to(BidSection.class);
        QueryWrapper<BidSection> bidSectionQueryWrapper = section.buildWrapper();

        BidSectionManager sectionManager = bidSection.to(BidSectionManager.class);

        // 添加其他的查询条件
        sectionManager.buildQueryType(bidSectionQueryWrapper, bidSection.getProjectId());


        if (null != bidSection.getByClarificationSubmissionEndTime() && bidSection.getByClarificationSubmissionEndTime() == 1) {
            bidSectionQueryWrapper.ge("clarification_submission_end_time", DateUtil.dateFormat(new Date()));
        }
        return list(bidSectionQueryWrapper);
    }

    /**
     * 插叙指定公告下的标段列表
     *
     * @param noticeId
     * @return
     * @update zhaojk
     */
    @Override
    public List<BidSectionDTO> findBidSectionsByNoticeId(Long noticeId) {
        if (noticeId == null) {
            return CollUtil.list(false);
        }
        return baseMapper.findBidSectionsByNoticeId(noticeId);
    }

    /**
     * @param bidSection:
     * @Description: 投标人查询项目大厅列表
     * @Author: zhongdl
     * @Date:2021/12/31 16:22
     * @return: {@link PageResult< BidSectionDTO> }
     **/
    @Override
    public PageResult<BidSectionDTO> pageProjectHall(BidSectionDTO bidSection) {
        PageResult<BidSectionDTO> bidSectionDTOPageResult = this.pageMyProject(bidSection, 1);
        return bidSectionDTOPageResult;
    }

    /**
     * @param bidSection:
     * @param type:1      项目大厅条件 2 我的项目条件
     * @Description:投标人我的项目 (1):需要报名的项目 报名成功 到 我的项目
     * (2 ):不需要报名的项目需要购买文件  购买完文件 到我的项目
     * (3 ): 不需要报名的项目不要购买文件 下载完文件 到 我的项目
     * @Author: zhongdl
     * @Date:2022/1/4 9:06
     * @return: {@link PageResult< BidSectionDTO> }
     **/
    @Override
    public PageResult<BidSectionDTO> pageMyProject(BidSectionDTO bidSection, Integer type) {
        Page<BidSectionDTO> pages = bidSection.pages();
        baseMapper.pageMyProject(pages, bidSection, type);
        if (CollUtil.isEmpty(pages.getRecords())) {
            return PageResult.get(pages);
        }
        NoticeService noticeService = SpringUtil.getBean(NoticeService.class);
        SupplyBidSignupMapper supplyBidSignupMapper = SpringUtil.getBean(SupplyBidSignupMapper.class);
        BidBuyRecordService bidBuyRecordService = SpringUtil.getBean(BidBuyRecordService.class);
        BidDownRecordService bidDownRecordService = SpringUtil.getBean(BidDownRecordService.class);

        for (BidSectionDTO record : pages.getRecords()) {
            if (Enums.equals(LogicEnum.NO, record.getSignUpFlag())) {
                record.setSignStartTime(null);
                record.setSignEndTime(null);
            }
            Long sectionId = record.getSectionId();
            //查询最后一次公告
            Notice notice = noticeService.lastNoticeBySectionId(sectionId);
            //公告标题
            record.setNoticeTitle(notice.getNoticeTitle());
            record.setNoticeId(notice.getId());
            //报名状态
            Integer signupStatus = supplyBidSignupMapper.findSignupFlagStatus(sectionId, record.getOrgId(), record.getBidderId());
            record.setSignupStatus(signupStatus);
            record.setSignupStatusName(Enums.nameOf(SignupStatusEnum.class, signupStatus));

            //是否下载
            Boolean downFlag = bidDownRecordService.downFlag(sectionId, record.getBidderId(), record.getOrgId());
            record.setDownLoadFlag(downFlag ? LogicEnum.YES.getCode() : LogicEnum.NO.getCode());

            // 标段状态名称
            record.setSectionStatusName(Enums.nameOf(SectionStatusEnum.class, SectionStatusEnum.getCodeById(record.getSectionStatus())));

            // 20220228标书售价为0时直接显示下载
            // 标书售价
            UserOrderService userOrderService = SpringUtil.getBean(UserOrderService.class);
            BigDecimal documentSalePrice = userOrderService.getPrice(sectionId, FeeTypeEnum.DOC_BOOK);
            // 标书售价
            if (NumberUtil.equals(documentSalePrice, BigDecimal.ZERO)) {
                record.setPayStatus(PayStatusEnum.PAY_SUCCESS.getCode());
            } else {
                // 查询支付状态
                Boolean flag = bidBuyRecordService.payFlag(sectionId, record.getBidderId(), record.getOrgId());
                record.setPayStatus(flag ? LogicEnum.YES.getCode() : LogicEnum.NO.getCode());
            }
        }
        return PageResult.get(pages);
    }

    /**
     * 根据企业ID（必填）查询所有的项目和对应的标段信息
     * 投标人投诉选择标段使用
     *
     * @param bidProjectDTO
     * @return
     * @Author: ljs
     * @Date:2022-2-8 10:30:54
     */
    @Override
    public List<AbstractProject> listMySection(BidProjectDTO bidProjectDTO) {
        // 查询该企业参与的所有项目
        List<AbstractProject> projectList = this.baseMapper.listSupplyBidSignup(bidProjectDTO);
        // 查询项目对应的标段
        for (AbstractProject project : projectList) {
            LambdaQueryWrapper<BidSection> sectionQueryWrapper = new LambdaQueryWrapper<>();
            sectionQueryWrapper.eq(BidSection::getProjectId, project.getId());
            List<BidSection> bidSectionList = list(sectionQueryWrapper);
            List<BidSectionDTO> sectionDTOS = new ArrayList<>();
            project.setTitle(project.getProjectName());
            for (BidSection section : bidSectionList) {
                BidSectionDTO sectionDTO = section.to(BidSectionDTO.class);
                sectionDTO.setTitle(section.getSectionName());
                sectionDTOS.add(sectionDTO);
            }
            project.setSections(sectionDTOS);
        }
        return projectList;
    }

    /**
     * 根据企业ID查询未递交投标文件的标段
     *
     * @param bidSectionDTO
     * @return
     * @Author: ljs
     * @Date:2022-2-18 18:17:52
     */
    @Override
    public Page<BidSectionDTO> pageNotSubmitSection(BidSectionDTO bidSectionDTO) {
        Page<BidSectionDTO> projectList = this.baseMapper.pageNotSubmitSection(bidSectionDTO.pages(), bidSectionDTO);
        return projectList;
    }

    @Override
    public PageResult<SupplyBidSignupDTO> pageSectionListByProjectId(Page page, Long projectId) {
        if (null == projectId) {
            return PageResult.get();
        }
        Page<SupplyBidSignupDTO> sectionDTOPage = baseMapper.pageSectionListByProjectId(page, projectId);
        return PageResult.get(sectionDTOPage);
    }

    @Override
    public PageResult<TenderInviteEnterpriseDTO> pageInvitationSectionListByProjectId(Page page, Long projectId) {
        if (null == projectId) {
            return PageResult.get();
        }
        Page<TenderInviteEnterpriseDTO> sectionDTOPage = baseMapper.pageInvitationSectionListByProjectId(page, projectId);
        return PageResult.get(sectionDTOPage);
    }

    /**
     * @param id:
     * @Description: 标段取消关联招标文件
     * @Author: zhongdl
     * @Date:2022/1/13 9:37
     * @return: {@link Boolean }
     **/
    @Override
    public Boolean cancelRelateFile(Long id) {
        if (id == null) {
            return false;
        }
        UpdateWrapper<BidSection> wrapper = new UpdateWrapper<>();
        wrapper.set("control_price", null)
                .set("price_Form", null)
                .set("bond", null)
                .set("bond_pay_type", null)
                .set("open_bid_time", null)
                .set("document_sale_start_time", null)
                .set("document_sale_end_time", null)
                .set("clarification_submission_end_time", null)
                .set("file_id", null)
                .set("section_status", SectionStatusEnum.NOTICE_DEPLOYED.getId())
                .eq("id", id);
        return update(wrapper);
    }

    /**
     * @param id:
     * @Description:根据标段id查询参加该项目的投标人
     * @Author: zhongdl
     * @Date:2022/2/19 9:31
     * @return: {@link List< Long> }
     **/
    @Override
    public List<Long> listParticipateSection(Long id) {
        return baseMapper.listParticipateSection(id);
    }

    /**
     * 根据月份查询 具有开标安排的日期
     *
     * @param bidSectionDTO
     * @return
     */
    @Override
    public List<BidSectionDTO> openDateList(BidSectionDTO bidSectionDTO) {
        Integer year = bidSectionDTO.getYear();
        Integer month = bidSectionDTO.getMonth();
        Long createId = bidSectionDTO.getCreateId();
        if (bidSectionDTO.getRoleSign() != null && bidSectionDTO.getRoleSign().equals(RoleSignEnum.BIDDER.getCode())) {
            List<BidSectionDTO> bidSectionDTOList = baseMapper.openDateListTender(year, month, createId);
            return bidSectionDTOList;
        } else {
            return baseMapper.openDateList(year, month, createId);
        }

    }

    /**
     * @param bidSectionDTO:
     * @Description:根据开标时间查询标段列表
     * @Author: zhongdl
     * @Date:2022/2/19 11:15
     * @return: {@link List< BidSectionDTO> }
     **/
    @Override
    public List<BidSectionDTO> listBidSectionByOpenBidTime(BidSectionDTO bidSectionDTO) {
        return baseMapper.listBidSectionByOpenBidTime(bidSectionDTO.getOpenBidTime());
    }

    /**
     * 获取标段的基本信息
     *
     * @param id
     * @return com.hb.core.pojo.project.section.dto.BidSectionDTO
     * @author tian
     * @date 2022-2-21 15:20
     */
    @Override
    public BidSectionDTO findBidSectionInfoById(Long id) {
        return baseMapper.findBidSectionInfoById(id);
    }

    /**
     * 根据投诉异议的ID查询对弈的标段信息
     *
     * @param clarifyId
     * @return
     */
    @Override
    public List<BidSectionDTO> listBidSectionByClarify(Long clarifyId) {
        return baseMapper.listBidSectionByClarify(clarifyId);
    }

    @Override
    public boolean refreshSectionStatusByFileId(Long fileId) {
        QueryWrapper<BidSection> wrapper = BidSection.wrapper();
        wrapper.eq("file_id", fileId);
        List<BidSection> sections = list(wrapper);
        for (BidSection section : sections) {
            BidSectionManager sectionManager = section.to(BidSectionManager.class);
            sectionManager.refreshBidSection();
        }
        return true;
    }

    @Override
    public boolean refreshSectionStatusByNoticeId(Long noticeId) {
        List<BidSectionDTO> sections = findBidSectionsByNoticeId(noticeId);
        for (BidSectionDTO section : sections) {
            BidSectionManager sectionManager = section.to(BidSectionManager.class);
            sectionManager.refreshBidSection();
        }
        return true;
    }

    @Override
    public boolean refreshSectionStatus(Long sectionId) {
        if (sectionId == null) {
            return false;
        }
        BidSection section = getById(sectionId);
        BidSectionManager sectionManager = section.to(BidSectionManager.class);
        sectionManager.refreshBidSection();
        return true;
    }

    /**
     * 根据项目id 查询所有通过报名的企业(门户使用)
     *
     * @param projectId
     * @return author：lsj
     */
    @Override
    public List<String> getTenderOrgByProjectId(@RequestBody String projectId) {
        List<String> orgNameList = this.baseMapper.getTenderOrgByProjectId(projectId);
        return orgNameList;
    }

    /**
     * 根据项目id 查询标段的递交数量
     *
     * @param bidSectionDTO
     * @return
     */
    @Override
    public Page<BidSectionDTO> listSubmitInfoByProjectId(BidSectionDTO bidSectionDTO) {
        Page<BidSectionDTO> pages = bidSectionDTO.pages();
        Page<BidSectionDTO> page = baseMapper.selectListByProjectId(pages, bidSectionDTO);
        if (CollUtil.isNotEmpty(page.getRecords())) {
            for (BidSectionDTO sectionDTO : page.getRecords()) {
                // 查询投标书
                QueryWrapper<BidSectionTender> bidSectionTenderQueryWrapper = new QueryWrapper<>();
                bidSectionTenderQueryWrapper.lambda().eq(BidSectionTender::getSectionId, sectionDTO.getId())
                        .eq(BidSectionTender::getStatus, "1");

                Long num = bidSectionTenderMapper.selectCount(bidSectionTenderQueryWrapper);
                sectionDTO.setSubmitNum(num.intValue());

                // 查询开标状态
                QueryWrapper<OpeningBidInfo> openingBidInfoQueryWrapper = new QueryWrapper<>();
                openingBidInfoQueryWrapper.lambda().eq(OpeningBidInfo::getSectionId, sectionDTO.getId());
                openingBidInfoQueryWrapper.orderByDesc("create_time").last("limit 1");
                OpeningBidInfo openingBidInfo = openingBidInfoMapper.selectOne(openingBidInfoQueryWrapper);

                // 解密后的投标人
                List<Long> decryptOrgIdList = new ArrayList();
                if (null != openingBidInfo) {
                    sectionDTO.setOpenBidStatus(openingBidInfo.getStatus());
                    // 查询解密后的投标人
                    List<BidSectionTenderDTO> bidSectionTender = bidSectionTenderMapper.listDecryptionBidSectionTender(sectionDTO.getId(), 1, 1);

                    decryptOrgIdList = bidSectionTender.stream().map(BidSectionTenderDTO::getId).collect(Collectors.toList());
                } else {
                    sectionDTO.setOpenBidStatus(0);
                }

                sectionDTO.setDecryptOrgIdList(decryptOrgIdList);
            }
        }
        return page;
    }

    @Override
    public List<BidSection> selectSectionByBidFileId(Long fileId) {
        QueryWrapper<BidSection> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BidSection::getFileId, fileId);
        List<BidSection> bidSections = this.baseMapper.selectList(queryWrapper);
        return bidSections;
    }

    @Override
    public BidSectionStatisticVO homepageSectionStatistic(StatisticUserParam statisticUserParam) {
        // 响应数据对象
        BidSectionStatisticVO bidSectionStatisticVO = new BidSectionStatisticVO();

        // 指定的用户ID
        Long userId = statisticUserParam.getUserId();

        if (userId == null) {
            return bidSectionStatisticVO;
        }

        // 项目总数
        int sectionCount = 0;
        // 已完成项目数量
        int sectionFinishedCount = 0;
        // 进行中的项目
        int sectionOngoingCount = 0;
        // 流标标段
        int failNum = 0;

        Integer roleSign = statisticUserParam.getRoleSign();
        if (roleSign == null) {
            log.warn("roleSign is null !");
            bidSectionStatisticVO.setOngoingSectionCount(0);
            bidSectionStatisticVO.setCompletedSectionCount(0);
            return bidSectionStatisticVO;
        }

        // 根据不同的用户角色对项目数量统计进行查询
        RoleSignEnum roleSignEnum = Enums.of(RoleSignEnum.class, roleSign);
        switch (roleSignEnum) {
            // 投标人/供应商
            case BIDDER:
                BidSectionDTO bidSection = new BidSectionDTO();
                bidSection.setCurrentPage(1);
                bidSection.setPageSize(1000);
                bidSection.setDataAuth(statisticUserParam.getDataAuth());

                // 复用我的项目的方法，查询显示在我的项目中的标段
                PageResult<BidSectionDTO> pageBidSection = pageMyProject(bidSection, 2);

                // 我的项目总数量
                sectionCount = pageBidSection.getTotal();

                // 查询已经完成的项目数量
                List<Long> ids = new ArrayList<>();
                for (BidSectionDTO bidSectionDTO : pageBidSection.getRecords()) {
                    ids.add(bidSectionDTO.getSectionId());
                }
                if (ids.size() > 0) {
                    sectionFinishedCount = bidSectionTenderMapper.countFinishedSectionByIds(ids);
                }
                break;
            // 招标人/采购人
            case TENDEREE:
                // 代理机构
            case AGENCY:
                RoleDataAuthEntity dataAuth = statisticUserParam.getDataAuth();
                List<Long> finishedStatusList = new ArrayList<>(Arrays.asList(SectionStatusEnum.WIN_BID_NOTICE_DEPLOYED.getId()));
                sectionFinishedCount = baseMapper.countSectionByDataAuth(dataAuth, finishedStatusList);
                // 查询流标标段数量
                QueryWrapper<BidSection> bidSectionQueryWrapper = new QueryWrapper<>();
                bidSectionQueryWrapper.lambda().eq(BidSection::getFailFlag, "1");
                failNum = Math.toIntExact(baseMapper.selectCount(bidSectionQueryWrapper));

                sectionCount = baseMapper.countSectionByDataAuth(dataAuth, null);
                break;
            default:
                break;
        }

        // 正在进行的项目数量
        sectionOngoingCount = sectionCount - sectionFinishedCount - failNum;

        bidSectionStatisticVO.setOngoingSectionCount(sectionOngoingCount);
        bidSectionStatisticVO.setCompletedSectionCount(sectionFinishedCount + failNum);

        return bidSectionStatisticVO;
    }


    /**
     * 查询标段的招标形式
     *
     * @param sectionId
     * @return java.lang.Integer
     * @author tian
     * @date 2022-4-20 10:27
     */
    @Override
    public Integer selectBidWayBySectionId(Long sectionId) {
        return baseMapper.selectBidWayBySectionId(sectionId);
    }

    /**
     * @Description: 查询邀请书标段列表
     *
     * 需要添加选中标记回显
     * 选中的标段默认拍到最前
     *
     * @author yuezheng
     * @param bidSectionDTO
     * @return java.util.List
     * @date 2022/6/27 16:19
     */
    @Override
    public List getBidSectionList(BidSectionDTO bidSectionDTO) {
        Set<Long> activeIdList = bidSectionDTO.getActiveIdList();
        Integer currentPage = bidSectionDTO.getCurrentPage();
        Integer pageSize = bidSectionDTO.getPageSize();

        QueryWrapper<BidSection> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().select(BidSection::getId, BidSection::getSectionName)
                .eq(BidSection::getProjectId, bidSectionDTO.getProjectId());
        if (!StringUtils.isEmpty(bidSectionDTO.getSectionName())) {
            queryWrapper.lambda().like(BidSection::getSectionName, bidSectionDTO.getSectionName());
        }
        List<BidSection> bidSectionList = baseMapper.selectList(queryWrapper);

        // 如果没有已选中则直接分页返回
        if (CollUtil.isEmpty(activeIdList)) {
            List<BidSection> bidSections = bidSectionList.stream().skip((currentPage - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
            return bidSections;
        }

        // 如果存在已选中 先设置选中标记 再根据标记排序 最后分页
        List<BidSectionDTO> result = bidSectionList.stream().map(item -> {
            BidSectionDTO dto = new BidSectionDTO();
            BeanUtils.copyProperties(item, dto);
            if (activeIdList.contains(item.getId())) {
                dto.setActive(1);
            } else {
                dto.setActive(0);
            }
            return dto;
        }).sorted((item1, item2) -> {
            return item1.getActive().compareTo(item1.getActive());
        }).skip((currentPage - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
        return result;
    }

    /**
     * @Description: 根据标段ID集合查询标段详情 附带该标段是否开标(openFlag)
     *
     * @author yuezheng
     * @param sectionIdList
     * @return java.util.List<com.hb.core.pojo.project.section.entity.BidSection>
     * @date 2022/6/27 16:21
     */
    @Override
    public List<BidSection> findBidSectionList(List<Long> sectionIdList) {
        return this.baseMapper.selectListByIds(sectionIdList);
    }
}
